package com.xyy.saas.payment.merchant.core.dto;

import com.alibaba.fastjson.JSONObject;
import com.xyy.saas.payment.common.Constants;
import com.xyy.saas.payment.common.enums.PictureEnum;
import com.xyy.saas.payment.common.exception.PaymentException;
import com.xyy.saas.payment.cores.enums.*;
import com.xyy.saas.payment.cores.param.PersonalAccountModifyParam;
import com.xyy.saas.payment.dao.model.ApplyAccountModify;
import com.xyy.saas.payment.merchant.core.vo.UserInfoVo;
import com.xyy.saas.payment.util.ApolloUtil;
import com.xyy.saas.payment.util.DateUtil;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import util.AESUtil;

@Getter
@Setter
public class PersonalAccountModifyDto {
    /**
     * 基础信息
     */
    // 业务线
    private BusinessIdTypeEnum businessIdType;
    // 业务侧商户标识
    private String businessId;
    // 回调地址
    private String callback;
    // 鉴权类型
    private InvokerEnum invoker;

    // 申请单号（业务不传）
    private String applyNo;
    // 支付平台侧商户标识（业务不传）
    private String accountId;
    // 申请来源 open_account,modify_account
    private String source = Constants.SOURCE_MODIFY_ACCOUNT;

    // 验证手机号，注册手机号
    private String mobile;

    /**
     * 开户人信息
     */
    // 证件签发日期
    private String cardStartDate;
    // 证件到期日期
    private String cardEndDate;
    // 户籍地址
    private String homeAddr;
    // 职业
    private String professional;
    // 身份证正面
    private String idCardFrontUrl;
    // 身份证反面
    private String idCardBackUrl;

    /**
     * 短信验证码
     */
    private String activeCode;

    /**
     * 参数转换
     */
    public static PersonalAccountModifyDto transfer(PersonalAccountModifyParam source) {
        // copy
        PersonalAccountModifyDto target = new PersonalAccountModifyDto();

        if(source != null) {
            BeanUtils.copyProperties(source, target);
        }

        return target;
    }

    /**
     * 参数转换(dto -> domain)
     */
    public ApplyAccountModify transfer() throws Exception {
        ApplyAccountModify applyAccountModify = new ApplyAccountModify();
        applyAccountModify.setApplyNo(applyNo);
        applyAccountModify.setAccountId(accountId);
        applyAccountModify.setBusinessIdType(businessIdType.getType());
        applyAccountModify.setStatus(AccountModifyStatusEnum.CREATE.getStatus());
        applyAccountModify.setMessage(AccountModifyStatusEnum.CREATE.getDesc());
        applyAccountModify.setCallback(callback);
        applyAccountModify.setType(Constants.PERSONAL);
        applyAccountModify.setSource(source);
        applyAccountModify.setMobile(AESUtil.encrypt(getMobile(), ApolloUtil.getProperty(Constants.USER_INFO_KEY)));
        applyAccountModify.setCorporationInfo(AESUtil.encrypt(getCorporation(), ApolloUtil.getProperty(Constants.USER_INFO_KEY)));
        return applyAccountModify;
    }

    /**
     * 参数转换（domain -> dto）
     */
    public static PersonalAccountModifyDto transfer(ApplyAccountModify source) throws Exception {
        if(source == null) {
            return null;
        }

        PersonalAccountModifyDto result = new PersonalAccountModifyDto();
        result.setApplyNo(source.getApplyNo());
        result.setAccountId(source.getAccountId());
        result.setBusinessIdType(BusinessIdTypeEnum.type(source.getBusinessIdType()));
        result.setCallback(source.getCallback());
        result.setSource(source.getSource());
        result.setMobile(AESUtil.decrypt(source.getMobile(), ApolloUtil.getProperty(Constants.USER_INFO_KEY)));
        result.setCorporation(AESUtil.decrypt(source.getCorporationInfo(), ApolloUtil.getProperty(Constants.USER_INFO_KEY)));
        return result;
    }

    /**
     * 更新覆盖user_info信息
     */
    public void copy2UserInfo(UserInfoVo userInfoVo) {
        // 图片
        if(StringUtils.isNotBlank(idCardFrontUrl)) {
            userInfoVo.getPicInfo().put(String.valueOf(PictureEnum.PERSONAL_CERT_FRONT.getCode()), idCardFrontUrl);
        }

        if(StringUtils.isNotBlank(idCardBackUrl)) {
            userInfoVo.getPicInfo().put(String.valueOf(PictureEnum.PERSONAL_CERT_BACK.getCode()), idCardBackUrl);
        }

        // 开户人
        if(StringUtils.isNotBlank(homeAddr)) {
            userInfoVo.getBasicInfo().setAddress(homeAddr);
        }

        if(StringUtils.isNotBlank(cardStartDate)) {
            userInfoVo.getBasicInfo().getIdentityInfo().setValidFrom(cardStartDate);
        }

        if(StringUtils.isNotBlank(cardEndDate)) {
            userInfoVo.getBasicInfo().getIdentityInfo().setValidUntil(cardEndDate);
        }

        if(StringUtils.isNotBlank(professional)) {
            userInfoVo.getBasicInfo().getIdentityInfo().setProfession(cardEndDate);
        }

        // 审核状态
        userInfoVo.setAuditStatus(AccountCreateStatusEnum.PASS.getStatus());
        userInfoVo.setAuditStatus(AccountCreateStatusEnum.PASS.getDesc());

        // 更新时间
        userInfoVo.setUtime(DateUtil.now());
    }

    private String getCorporation() {
        JSONObject corporation = new JSONObject();

        if(StringUtils.isNotBlank(cardStartDate)) {
            corporation.put("cardStartDate", cardStartDate);
        }

        if(StringUtils.isNotBlank(cardEndDate)) {
            corporation.put("cardEndDate", cardEndDate);
        }

        if(StringUtils.isNotBlank(homeAddr)) {
            corporation.put("homeAddr", homeAddr);
        }

        if(StringUtils.isNotBlank(professional)) {
            corporation.put("professional", professional);
        }

        if(StringUtils.isNotBlank(idCardFrontUrl)) {
            corporation.put("idCardFrontUrl", idCardFrontUrl);
        }

        if(StringUtils.isNotBlank(idCardBackUrl)) {
            corporation.put("idCardBackUrl", idCardBackUrl);
        }

        return corporation.toJSONString();
    }

    private void setCorporation(String corporation) {
        if(StringUtils.isBlank(corporation)) {
            return;
        }

        JSONObject object = JSONObject.parseObject(corporation);
        setCardStartDate(object.getString("cardStartDate"));
        setCardEndDate(object.getString("cardEndDate"));
        setHomeAddr(object.getString("homeAddr"));
        setProfessional(object.getString("professional"));
        setIdCardFrontUrl(object.getString("idCardFrontUrl"));
        setIdCardBackUrl(object.getString("idCardBackUrl"));
    }

    /**
     * 参数校验
     */
    public void checkParam() throws PaymentException {
        if(businessIdType == null) {
            throw new PaymentException(ResultCodeEnum.PARAM_ERROR.getCode(), "业务线（businessIdType）不能为空");
        }

        if(StringUtils.isBlank(businessId)) {
            throw new PaymentException(ResultCodeEnum.PARAM_ERROR.getCode(), "商户标识（businessId）不能为空");
        }

        if(StringUtils.isBlank(callback)) {
            throw new PaymentException(ResultCodeEnum.PARAM_ERROR.getCode(), "回调（callback）不能为空");
        }

        if(StringUtils.isBlank(mobile)) {
            throw new PaymentException(ResultCodeEnum.PARAM_ERROR.getCode(), "验证手机号（mobile）不能为空");
        }

        if(StringUtils.isBlank(activeCode)) {
            throw new PaymentException(ResultCodeEnum.PARAM_ERROR.getCode(), "验证码（activeCode）不能为空");
        }
    }
}
